﻿using MediatR;
using W.Carrier.Domain;
using W.Carrier.Domain.PageDTO;
using W.Carrier.Read.Api.Application.Command;
using W.Carrier.Repostiory.Interface;

namespace W.Carrier.Read.Api.Application.CommandHandler
{
    public class CarrierShowCommandHandler:IRequestHandler<CarrierShowCommand, PageInfo<CarrierInfo>>
    {
        private readonly ICarrierInfoRepository _icarrierInfoRepository;
        public CarrierShowCommandHandler(ICarrierInfoRepository icarrierInfoRepository)
        {
            _icarrierInfoRepository = icarrierInfoRepository;
        }

        public async Task<PageInfo<CarrierInfo>> Handle(CarrierShowCommand request, CancellationToken cancellationToken)
        {
            PageInfo<CarrierInfo> page = new PageInfo<CarrierInfo>();
            var list = await _icarrierInfoRepository.GetAsync(c=>c.IsDelete==false);
            if (!string.IsNullOrEmpty(request.CarrierNo))
            {
                list=list.Where(c=>c.CarrierNo==request.CarrierNo).ToList();
            }
            if (!string.IsNullOrEmpty(request.CarrierName))
            {
                list = list.Where(c => c.CarrierName .Contains(request.CarrierName)).ToList();
            }
            page.TotalCount = list.Count();
            page.TotalPage = (int)Math.Ceiling(page.TotalCount*1.0/request.PageSize);
            page.List=list.OrderByDescending(c=>c.CarrierId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            return page;
        }
    }
}
